package com.ds.core.support.qiniu;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.BucketManager.FileListIterator;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;

public class Manager {

	/**
	 * 获取文件信息
	 * @param zone
	 * @param key
	 * @param auth
	 * @param bucket
	 * @return
	 */
	public static FileInfo getFileInfo(Zone zone,String key,Auth auth,String bucket) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(zone);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
			FileInfo fileInfo = bucketManager.stat(bucket, key);
			System.out.println(fileInfo.hash);
			System.out.println(fileInfo.fsize);
			System.out.println(fileInfo.mimeType);
			System.out.println(fileInfo.putTime);
			return fileInfo;
		} catch (QiniuException ex) {
			System.err.println(ex.response.toString());
		}
		return null;
	}

	/**
	 * 修改文件类型
	 * @param zone
	 * @param key
	 * @param auth
	 * @param bucket
	 * @param newMimeType
	 */
	public static void editFileType(Zone zone,String key,Auth auth,String bucket,String newMimeType) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(zone);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		// 修改文件类型
		try {
			bucketManager.changeMime(bucket, key, newMimeType);
		} catch (QiniuException ex) {
			System.out.println(ex.response.toString());
		}
	}

	/**
	 * 移动文件
	 * @param zone
	 * @param auth
	 * @param fromBucket
	 * @param fromKey
	 * @param toBucket
	 * @param toKey
	 */
	public static void move(Zone zone,Auth auth,String fromBucket,String fromKey,String toBucket,String toKey) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(zone);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
			bucketManager.move(fromBucket, fromKey, toBucket, toKey);
		} catch (QiniuException ex) {
			// 如果遇到异常，说明移动失败
			System.err.println(ex.code());
			System.err.println(ex.response.toString());
		}
	}

	/**
	 * 复制文件
	 * @param zone
	 * @param auth
	 * @param fromBucket
	 * @param fromKey
	 * @param toBucket
	 * @param toKey
	 */
	public static void copy(Zone zone,Auth auth,String fromBucket,String fromKey,String toBucket,String toKey) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(zone);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
			bucketManager.copy(fromBucket, fromKey, toBucket, toKey);
		} catch (QiniuException ex) {
			// 如果遇到异常，说明复制失败
			System.err.println(ex.code());
		}
	}

	/**
	 * 刪除文件
	 * @param key
	 * @param auth
	 * @param bucket
	 */
	public static void delete(Zone zone,String key,Auth auth,String bucket) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(zone);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
			bucketManager.delete(bucket, key);
		} catch (QiniuException ex) {
			// 如果遇到异常，说明删除失败
			System.err.println(ex.code());
			System.err.println(ex.response.toString());
		}
	}

	/**
	 * 设置文件生命周期
	 * @param zone
	 * @param key
	 * @param auth
	 * @param bucket
	 */
	public static void setAliveTime(Zone zone,String key,Auth auth,String bucket,int days) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(zone);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
			bucketManager.deleteAfterDays(bucket, key, days);
		} catch (QiniuException ex) {
			System.err.println(ex.response.toString());
		}
	}

	/**
	 * 获取文件列表
	 * @param zone
	 * @param auth
	 * @param bucket
	 * @param prefix  文件名前缀
	 * @param limit   每次迭代的长度限制，最大1000，推荐值 1000
	 * @param delimiter  指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
	 * @return
	 */
	public static FileListIterator getFileList(Zone zone,Auth auth,String bucket,String prefix,int limit,String delimiter) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(zone);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		// 列举空间文件列表
		BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit,
				delimiter);
		while (fileListIterator.hasNext()) {
			// 处理获取的file list结果
			FileInfo[] items = fileListIterator.next();
			if (items==null) {
				break;
			}
			for (FileInfo item : items) {
				System.out.print(item.key+"\t");
				System.out.print(item.hash+"\t");
				System.out.print(item.fsize+"\t");
				System.out.print(item.mimeType+"\t");
				System.out.print(item.putTime+"\t");
				System.out.print(item.endUser);
				System.out.println();
			}
			System.out.println("下一批：");
		}
		return fileListIterator;
	}

	/**
	 * 抓取网络资源到空间
	 * @param zone
	 * @param auth
	 * @param bucket
	 * @param key
	 * @param remoteSrcUrl
	 * @return
	 */
	public static FetchRet fetchToSpace(Zone zone,Auth auth,String bucket,String key,String remoteSrcUrl) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(zone);
		//String remoteSrcUrl = "http://devtools.qiniu.com/qiniu.png";
		BucketManager bucketManager = new BucketManager(auth, cfg);
		// 抓取网络资源到空间
		try {
			FetchRet fetchRet = bucketManager.fetch(remoteSrcUrl, bucket, key);
			System.out.println(fetchRet.hash);
			System.out.println(fetchRet.key);
			System.out.println(fetchRet.mimeType);
			System.out.println(fetchRet.fsize);
			return fetchRet;
		} catch (QiniuException ex) {
			System.err.println(ex.response.toString());
		}
		return null;
	}
	
	/**
	 * 回调验证
	 * @param auth
	 * @param callbackUrl
	 * @param callbackBodyType
	 * @param callbackAuthHeader
	 * @param callbackBody
	 */
	public static void callbackValid(Auth auth,String callbackUrl,String callbackBodyType,String callbackAuthHeader,byte[] callbackBody) {

		/*
		 * 这两个参数就是在定义PutPolicy参数时指定的内容
		 */
		// 回调地址
		//String callbackUrl = "http://api.example.com/qiniu/callback";
		// 定义回调内容的组织格式，与上传策略中的callbackBodyType要保持一致
		// String callbackBodyType = "application/x-www-form-urlencoded";
		// //回调鉴权的签名包括请求内容callbackBody
		//String callbackBodyType = "application/json";// 回调鉴权的签名不包括请求内容
		/**
		 * 这两个参数根据实际所使用的HTTP框架进行获取
		 */
		// 通过获取请求的HTTP头部Authorization字段获得
		//String callbackAuthHeader = "xxx";
		// 通过读取回调POST请求体获得，不要设置为null
		//byte[] callbackBody = null;
		// 检查是否为七牛合法的回调请求
		boolean validCallback = auth.isValidCallback(callbackAuthHeader, callbackUrl, callbackBody, callbackBodyType);
		if (validCallback) {
			// 继续处理其他业务逻辑
		} else {
			// 这是哪里的请求，被劫持，篡改了吧？
		}
	}

	public static void main(String[] args) {
		//getFileInfo(Zone.zone0(),"Fq8KWehX83XY29Ct1WNNDF_63IRv",CredentialsManager.getAuth(),"ds-literary");
		//editFileType(Zone.zone0(), "Fu3P9AgpOo_0q_4KnJdn9ZXVimfD", CredentialsManager.getAuth(), "ds-literary", "txt");
//		delete(Zone.zone0(), "Fu3P9AgpOo_0q_4KnJdn9ZXVimfD", CredentialsManager.getAuth(), "ds-literary");
//		move(Zone.zone0(),CredentialsManager.getAuth(),"fromBucket","fromKey","toBucket","toKey");
//		copy(Zone.zone0(),CredentialsManager.getAuth(),"fromBucket","fromKey","toBucket","toKey");
//		setAliveTime(Zone.zone0(),"Fq8KWehX83XY29Ct1WNNDF_63IRv",CredentialsManager.getAuth(),"ds-literary",1);
		//getFileList(Zone.zone0(),CredentialsManager.getAuth(),"ds-literary","aaa",2,"");
		fetchToSpace(Zone.zone0(),CredentialsManager.getAuth(),"ds-literary",null,"http://devtools.qiniu.com/qiniu.png");

	}
}
